package cn.well.cloud.quartz.core.task;

import cn.well.cloud.quartz.core.task.api.OperationAPI;
import cn.well.cloud.quartz.core.task.exception.TaskApiException;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by wison on 2020/7/01.
 */
@Slf4j
@Component
public class ResultHandler {

    public Object handle(OperationAPI operationAPI) {
        Object result = null;
        try {
            result = operationAPI.invokeOperationAPI();
        } catch (TaskApiException e) {
            if (e.getCode() == 401) {

                return result;
            }
            if (e.getCode() >= 500) {
                log.info("The server connection failed and is being reconnected");
                result = retry(operationAPI);
                if (result != null) {
                    return result;
                }
                System.out.println(e);
                log.error("The server may be faulty. Please try again later");
            }
        }catch (SchedulerException e2) {
            log.error("The task inner error:"+e2.getMessage());
        }
        return result;
    }

    /**
     * 重连
     * @param operationAPI
     * @return
     */
    public Object retry(OperationAPI operationAPI) {
        Object result = null;
        long time = 5;
        for (int i = 0; i < 3; i++) {
            try {
                TimeUnit.SECONDS.sleep(time);
                log.info("Reconnection is in progress..." + i);
                result = operationAPI.invokeOperationAPI();
                if (result != null) {
                    return result;
                }
            } catch (TaskApiException e1) {
                time *= 3;
            } catch (InterruptedException e1) {
                log.error(e1.getMessage());
            }catch (SchedulerException e2) {
                log.error("The task inner error:"+e2.getMessage());
            }
        }
        return result;
    }
}
